//跳转URL
function jumpurl (url) {
	loading();
	jumpurl_handle = setTimeout(function(){
		clearTimeout(jumpurl_handle);
		if(url){
			location.href = url;
		}else{
			removeLoading();
			history.go(-1);
		}
	},0);
}
/**
 * 编辑器图片文件方式上传
 * @param file
 * @param editor
 */
function upload_editor_image(file, editor_id){
	loading();
	data = new FormData();
	data.append("file", file);
	$.ajax({
		data: data,
		type: "POST",
		dataType : 'json',
		url: "/File/upload?update_type=img",
		cache: false,
		contentType: false,
		processData: false,
		success: function(data) {
			removeLoading();
			if(data.status != 200){
				msgbox(data.info, 'error')
				return false;
			}
			img_url = data.data.file_url;
			$('#' + editor_id).summernote('insertImage', img_url, function ($image) {
				$image.css('width', $image.width() / 2);
				$image.addClass('img-responsive');
			});
		},
		error:function(){
			removeLoading();
			msgbox('请求失败！', 'error');
		}
	});
}

function loading(){
	removeLoading();
	$("body").append("<div class='loading-box' id='loading'><div class='icon-logo'></div><div class='loading'></div></div>");
	var left = ($(document).outerWidth() - $('#loading').outerWidth()) / 2;
	var top  = ($(window).outerHeight() - $('#loading').outerHeight()) / 2;
		left = left - 10;
		top  = top - 30;
	$("#loading").css({left:left + 'px'});
	$("#loading").css({top:top + 'px'});
}

function money_format(money) {
	if(isNaN(money)){
		return money;
	}
	money = (Math.round((money - 0) * 100)) / 100;
	money = (money == Math.floor(money)) ? money + ".00" : ((money * 10 == Math.floor(money * 10)) ? money + "0" : money);
	money = String(money);
	var ps = money.split('.');
	var whole = ps[0];
	var sub = ps[1] ? '.' + ps[1] : '.00';
	var r = /(\d+)(\d{3})/;
	while (r.test(whole)) {
		whole = whole.replace(r, '$1' + ',' + '$2');
	}
	money = whole + sub;

	return money;
}

/**
 * JS消息盒子
 * @param msg 信息
 * @param type 类型，有warn、success、error默认为success
 * @param redirect 重定向地址
 * @param timeout 缓冲时间，默认3秒
 * @return
 */
function msgbox(msg,type,redirect,timeout){
	removeLoading();
	$("#msgbox-div").remove();
	type = type ? type : 'success';
	msg = msg ? msg : '数据操作成功！';
	var left = ($(document).width()-240)/2;
	$("body").append("<div id='msgbox-div' class='msgbox-" + type +"'><i class='icon-" + type + "'></i>" + msg +"</div>");
	loading_w = $("#msgbox-div").outerWidth();
	var left = ($(window).width() - loading_w) / 2;
	$("#msgbox-div").css({left:left + 'px'});

	timeout = parseInt(timeout);
	timeout = timeout>0 ? timeout : 3;
	var handle = setTimeout(function(){
		$("#msgbox-div").remove();
		clearTimeout(handle);
		if(redirect) document.location.href = redirect;
	},timeout * 1000);
}


function removeLoading(){
	$("#loading").remove();
}

$(document).ready(function(){
	// 密码MD5加密
	$('form').on('submit', function () {
		$('input[type="password"]').each(function () {
			if(!$(this).hasClass('not-md5') && $(this).val()){
				var password     = $(this).val();
				var password_md5 = $.md5(password);
				$(this).val(password_md5);
			}
		});
	});
	// 图片验证码更换
	$(document).on('click', '.img-verify', function () {
		var url = $(this).attr('href') + '?' + Math.random();
		$(this).attr('src', url);
		return false;
	});
	//获取验证码
	$(document).on('click', '.get-smscode', function () {
		var mobile   = $('input[name="mobile"]').val();
		var imgcode  = $('input[name="imgcode"]').val();
		var url      = $(this).attr('url');
		var sms_type = $(this).attr('sms-type');
			sms_type = sms_type ? sms_type : 'register';
		if(!url){
			msgbox('URL未配置！', 'error');
			return false;
		}
		if(!mobile){
			msgbox('手机号不能为空！', 'error');
			return false;
		}
		if(!imgcode){
			msgbox('图片验证码不能为空！', 'error');
			return false;
		}
		loading('获取验证码中...');
		$.ajax({
			type: "get",
			url: url,
			data: 'type=' + sms_type + '&mobile=' + mobile + '&imgcode=' + imgcode,
			dataType: "json",
			success: function(data){
				removeLoading();
				if(data.code == 1){
					$('.get-smscode').hide();
					$('.smscode-time').css('display', 'inline-block').find('span').text(60);
					msgbox(data.msg);
					var wait = $('.smscode-time span');
					var smscode_interval = setInterval(function(){
						var time = wait.text();
							--time;
							wait.text(time);
						if(time == 0) {
							$('.smscode-time').hide();
							$('.get-smscode').show();
							clearInterval(smscode_interval);
						};
					}, 1000);
				}else{
					// 更换验证码
					var url = $('.img-verify').attr('href') + '?' + Math.random();
					$('.img-verify').attr('src', url);
					msgbox(data.msg, 'error');
				}
			},
			error : function () {
				removeLoading();
				msgbox('请求失败！', 'error');
			}
		});
	});
	//弹窗JS
	$.getScript("/public/js/jquery-plugin/win/win.extend.js", function () {
		// 弹出窗口
		$(document).on('click', ".win", function(){
			$(this).win();
			return false;
		});
	});
	// 加载表单验证
	$.getScript("/public/js/jquery-plugin/validate/init.js");
	//ajax表单提交
	$(document).on('submit', 'form.ajax-form', function () {
		var url    = $(this).attr('action');
			url    = url ? url : window.location.href;
		var method = $(this).attr('method');
		var method = method ? method : 'post';
		var data   = $(this).serialize();

		loading('正在提交，请稍候...');
		$.ajax({
			url : url,
			data : data,
			type : method == 'post' ? 'post' : 'get',
			dataType:'json',
			success : function(json){
				if(json.code == 1){
					msgbox(json.msg);
				}else{
					msgbox(json.msg,'error');
				}
				//有返回链接，则跳转
				if(json.url){
					jumpurl(json.url);
				}
			},
			error : function (data) {
				msgbox('请求失败，请稍候再试！', 'error');
			}
		});
		return false;
	});
	//表单提交
	$(document).on('click', '.form-submit', function () {
		var action    = $(this).attr('action');
			action    = action ? action : ($(this).attr('href') ? $(this).attr('href') : window.location.href);
		var method    = $(this).attr('method');
		var container = $(this).attr('form');

		form_html = container ? $('.' + container).html() : $('form').html();
		if(form_html){
			var html = "<form class='tmp-form' novalidate='true' action='" + (action ? action : '') + "' method='" + (method ? method : 'post') + "'>" + form_html + "</form>";
			$(html).submit();
		}
		return false;
	});
	$(document).on('click', '.form-submit-data', function () {
		var form_class = $(this).attr('form');
		var form_data  = form_class ? $('form.' + form_class).serialize() : $(this).parentsUntil('form').parent().serialize();
		var action     = $(this).parentsUntil('form').parent().attr('action');
		var method     = $(this).parentsUntil('form').parent().attr('method');
		var attr_data  = $(this).attr('form-data');
		var new_data   = form_data + '&' + attr_data;
		var form_url   = action ? action : ($(this).attr('action') ? $(this).attr('action') : $(this).attr('href'));
		var method     = method ? method : $(this).attr('method');
			form_url   = form_url ? form_url : window.location.href;

		loading('正在提交，请稍候...');
		$.ajax({
			url : form_url,
			data : new_data,
			type : method ? method : 'post',
			dataType:'json',
			success : function(json){
				if(json.code == 1){
					msgbox(json.msg);
				}else{
					msgbox(json.msg, 'error');
				}
				//有返回链接，则跳转
				if(json.url){
					jumpurl(json.url);
				}
			},
			error : function (data) {
				msgbox('请求失败，请稍候再试！', 'error');
			}
		});
		return false;
	});
	//打印处理
	if($(".btn-print").size()){
		$.getScript("/public/js/jquery-plugin/jquery.jqprint-0.3.js", function () {
			$(".btn-print").click(function(){
				var container = $(this).attr('for');
					container = container ? '.' + container : 'body';
				$(container).jqprint(); 
			});
		});
	}

	//跳转链接
	$(document).on('click', '.jump', function () {
		var url = $(this).attr('href');
		var url = url ? url : $(this).attr('url');
		jumpurl(url);
		return false;
	});

	//加载更多
	$(document).on('click', ".load-more", function () {
		loading();
		var here    = $(this);
		var url     = here.attr('url');
		var data_to = here.attr('data-to');
		if(!url){
			msgbox('URL未配置！', 'error');
		}
		$.ajax({
			type: "get",
			url: url,
			dataType:"json",
			success: function(data){
				if(data.code == 1){
					$("." + data_to).append(data.data.html);
					next_url = data.data.page.ajax_next_page;
					if(next_url){
						here.attr('url', next_url);
					}else{
						msgbox('到底了');
						here.remove();
					}
				}
			},
			error : function () {
				msgbox('请求失败，请稍候再试！', 'error');
			}
		});
	});
	// AJAX分页
	$(document).on('click', '.ajax-page a', function () {
		var here    = $(this);
		var url     = here.attr('href');
			url     = url ? url : here.attr('url');
		var data_to = here.parent().attr('data-to');

		loading();
		$.ajax({
			type: "get",
			url: url,
			dataType:"json",
			success: function(data){
				if(data.code == 1){
					$("." + data_to).html(data.data.html);
					here.parent().html(data.data.page_html);
				}else{
					msgbox(data.msg, 'error');
				}
			},
			error : function () {
				removeLoading();
				msgbox('请求失败，请稍候再试！', 'error');
			}
		});
		return false;
	});

	// 选择省份处理
	$(document).on('change', '.ajax-province-change', function () {
		var request_url  = $(this).attr('ajax-url');
		var uniqid       = $(this).attr('uniqid');
		var province_id  = $(this).val();
		var city_option  = '<option value="">-城市-</option>';
		var area_option  = '<option value="">-地区-</option>';
		var is_have_city = $('.ajax-city-change').size();
		$('.ajax-city-change[uniqid="' + uniqid + '"]').html(city_option).hide();
		$('.ajax-area-change[uniqid="' + uniqid + '"]').html(area_option).hide();
		if(!province_id || !request_url || !is_have_city){
			return false;
		}
		loading();
		$.ajax({
			url : request_url,
			data : 'parent_id=' + province_id,
			type : 'get',
			dataType:'json',
			success : function(json){
				removeLoading();
				if(json.code == 1){
					var list = json.data.list;
					$.each(list, function(i){
						area_id = list[i]['area_id'];
						name    = list[i]['name'];
						city_option += '<option value="' + area_id + '">' + name + '</option>';
					});
					$('.ajax-city-change[uniqid="' + uniqid + '"]').html(city_option).show();
				}
			},
			error : function () {
				removeLoading();
				msgbox('请求失败，请稍候再试！', 'error');
			}
		});
	});
	// 选择城市处理
	$(document).on('change', '.ajax-city-change', function () {
		var request_url  = $(this).attr('ajax-url');
		var uniqid       = $(this).attr('uniqid');
		var city_id      = $(this).val();
		var area_option  = '<option value="">-地区-</option>';
		var is_have_area = $('.ajax-area-change').size();
		$('.ajax-area-change[uniqid="' + uniqid + '"]').html(area_option).hide();
		if(!city_id || !request_url || !is_have_area){
			return false;
		}
		loading();
		$.ajax({
			url : request_url,
			data : 'parent_id=' + city_id,
			type : 'get',
			dataType:'json',
			success : function(json){
				removeLoading();
				if(json.code == 1){
					var list = json.data.list;
					$.each(list, function(i){
						area_id = list[i]['area_id'];
						name    = list[i]['name'];
						area_option += '<option value="' + area_id + '">' + name + '</option>';
					});
					$('.ajax-area-change[uniqid="' + uniqid + '"]').html(area_option).show();
				}
			},
			error : function () {
				removeLoading();
				msgbox('请求失败，请稍候再试！', 'error');
			}
		});
	});
	// 选择城市处理
	$(document).on('change', '.ajax-area-change', function () {
		var request_url    = $(this).attr('ajax-url');
		var area_id        = $(this).val();
		var street_option  = '<option value="">-街道-</option>';
		var is_have_street = $('.ajax-street-change').size();
		$('.ajax-street-change').html(street_option);
		if(!area_id || !request_url || !is_have_street){
			return false;
		}
		loading();
		$.ajax({
			url : request_url,
			data : 'parentid=' + area_id,
			type : 'get',
			dataType:'json',
			success : function(json){
				removeLoading();
				if(json.code == 1){
					var list = json.data.list;
					$.each(list, function(i){
						area_id = list[i]['area_id'];
						name    = list[i]['name'];
						street_option += '<option value="' + area_id + '">' + name + '</option>';
					});
					$('.ajax-street-change').html(street_option).show();
				}
			},
			error : function (data) {
				msgbox('请求失败，请稍候再试！', 'error');
			}
		});
	});
	// AJAX 复选框选择
	$(document).on('click', '.ajax_checkbox', function () {
		var url  = $(this).attr('url');
		var name = $(this).attr('name');
			name = name ? name : '';
		data = 'field=' + name;
		loading('正在修改，请稍候...');
		$.ajax({
			url : url,
			data : data,
			type : 'get',
			dataType:'json',
			success : function(json){
				if(json.code == 1){
					msgbox(json.msg);
				}else{
					msgbox(json.msg, 'error');
				}
			},
			error : function (data) {
				msgbox('请求失败，请稍候再试！', 'error');
			}
		});
	});

	//查看大图
	if($('.view_big_pic').size() || $('.upload-list').size()){
		$.getScript("/public/js/jquery-plugin/fancyBox/jquery.fancybox.pack.js?v=2.1.5",function () {
			$("<link>").attr({ 
				rel: "stylesheet",
				type: "text/css",
				href: "/public/js/jquery-plugin/fancyBox/jquery.fancybox.css?v=2.1.5"
			}).appendTo("head");
			//点击图片，查看大图
			$('.view_big_pic').fancybox();
		});
	}

	//操作提示
	$(document).on('click', ".opt-tip", function(){
		var here = $(this);
		var url  = $(this).attr('url');
			url  = url ? url : $(this).attr('href');
		var tourl       = $(this).attr('jumpurl');
		var del_mod     = $(this).attr('del-class');
		var add_class   = $(this).attr('add-class');
		var loading_tip = $(this).attr('tip-loading');
			loading_tip = loading_tip ? loading_tip : '正在操作，请稍候...';
			add_class   = add_class ? add_class : 'on';
		var unon_text   = $(this).attr('unon-text');
		var on_text     = $(this).attr('on-text');
		var success_callback = $(this).attr('success-callback');
		var error_callback   = $(this).attr('error-callback');
		var is_return        = $(this).attr('is-return');
		if (!url) {
			return false;
		}
		loading(loading_tip);
		$.ajax({
			type: "get",
			url: url,
			dataType: "json",
			success : function(data){
				removeLoading();
				if(data.code == 1){
					if(data.msg){
						msgbox(data.msg);
					}
					if(tourl){
						jumpurl(tourl);
					}
					if(data.url){
						jumpurl(data.url);
					}
					if(del_mod){
						$('.' + del_mod).fadeOut('slow', function () {
							$('.' + del_mod).remove();
						});
					}
					if(here.hasClass(add_class)){
						here.removeClass(add_class);
						here.text(unon_text);
					}else{
						here.addClass(add_class);
						here.text(on_text);
					}
					var node_id     = data.data.node_id;
					var node_data   = data.data.node_data;
					var del_node_id = data.data.del_node_id;
					if(node_id && node_data){
						$.each(node_data , function(key, value){
							$('.'+node_id).find('.'+key).html(value);
						});
					}
					if(del_node_id){
						$('.'+del_node_id).remove();
					}
					if(success_callback){
						eval(success_callback);
					}
					
				}else{
					msgbox(data.msg, 'error');
					if(error_callback){
						eval(error_callback);
					}
					if(data.url){
						jumpurl(data.url, 2);
					}
				}
			},
			error :function (data) {
				removeLoading();
				msgbox('请求失败，请稍候再试！', 'error');
				if(error_callback){
					eval(error_callback);
				}
			}
		});
		if(!is_return){
			return false;
		}
	});

	//确认操作
	$(document).on('click', ".btn-confirm-opt", function () {
		var checkbox  = $(this);
		var url       = $(this).attr('url');
		var del_mod   = $(this).attr('del-class');
		var msg       = $(this).attr('msg');
		var method    = $(this).attr('method');
		var label_mod = $(this).attr('label-class');
		var here      = $(this);

		url = url ? url : $(this).attr('href');
		msg = msg ? msg : '您确认要进行此操作吗？';

		html  = '<div style="width:300px;" class="confirm-opt-box">';
		html += '<div>' + msg + '</div>';
		html += '<div style="text-align:center;margin-top:8px"><span class="btn btn-warning confirm">确定</span> <span class="btn btn-default" onclick="$.winRemove()">取消</span></div>';
		html += '</div>';
		$.win_info('', html, '提示信息');
		$('.confirm-opt-box .confirm').bind('click', function () {
			loading('正在处理，请稍候...');
			$.ajax({
				type: method ? method : 'get',
				url: url,
				dataType: 'json',
				success: function(data){
					$.winRemove();
					if(data.code == 1){
						msgbox(data.msg);
						$('.' + del_mod).fadeOut('slow', function () {
							$('.' + del_mod).remove();
						});
						if(checkbox.attr('checked')){
							checkbox.removeAttr('checked');
						}else{
							checkbox.attr('checked', 'checked');
						}
						if(data.url){
							jumpurl(data.url);
						}
						if(data.data.label || data.data.label == 0){
							if(label_mod){
								$('.' + label_mod).text(data.data.label);
							}else{
								here.text(data.data.label);
							}
						}
					}else{
						msgbox(data.msg, 'error');
					}
				},
				error : function () {
					msgbox('请求失败，请稍候再试！', 'error');
				}
			});
		})
		return false;
	});

	
	//星级评分
	$(document).on('mousemove', '.rating', function (e) {
		var offset    = $(this).offset().left;
		var curoffset = e.pageX - offset;
		var value     = (curoffset / $(this).width()) * 100;
		if(value <= 20){
			val = 1;
		}
		else if(value > 20 && value <= 40){
			val = 2;
		}
		else if(value > 40 && value <= 60){
			val = 3;
		}
		else if(value > 60 && value <= 80){
			val = 4;
		}else{
			val = 5;
		}
		$(this).find('.star').removeClass('on');
		$(this).find('.star:lt(' + val + ')').addClass('on');
		$(this).find('input').val(val);
	});

	// AJAX 修改input内容更新保存
	$('.ajax-update-field').on('focusout', function() {
		var request_url = $(this).attr('url') ? $(this).attr('url') : $(this).attr('href');
		var content     = $(this).val();
		if(!request_url){
			msgbox('请求URL未配置！', 'error');
			return false;
		}
		loading();
		$.ajax({
			url : request_url,
			data : 'content=' + content,
			type : 'post',
			dataType:'json',
			success : function(json){
				msgbox(json.msg);
			},
			error : function () {
				msgbox('请求失败，请稍候再试！', 'error');
			}
		});
	});
	// 自定义选择框
	$(document).on('click', '.select-box li', function () {
		var disabled     = $(this).parent().hasClass('disabled');
		var all_disabled = $(this).hasClass('disabled');
		var is_radio     = $(this).parent().hasClass('is-radio');
		var is_select    = $(this).hasClass('no-select');
		// 禁用处理
		if(disabled || is_select || all_disabled){
			return false;
		}
		// 单选处理
		if(is_radio){
			$(this).parent().find('li').removeClass('active');
			$(this).parent().find('input').removeAttr('checked');
		}
		if($(this).parent().hasClass('disable')){
			return false;
		}
		// 已选择，设置成未选择
		if($(this).hasClass('active')){
			$(this).removeClass('active');
			$(this).find('input').removeAttr('checked');
		}else{
			$(this).addClass('active');
			$(this).find('input').prop('checked', 'checked');
		}
	});
	// 自动保存表单数据插件
	if($('form[is-cache-data="true"]').size()){
		$.getScript("/public/js/jquery-plugin/sisyphus.min.js", function () {
			$('form[is-cache-data="true"]').sisyphus({
				timeout: 5
			});
		});
	}
	// 编辑器处理
	if($('.summernote_editor').size()){
		$('.summernote_editor').after('<p class="summernote-ueditor-loading">加载中，请稍候...</p>');
		$.getScript("/public/js/summernote/summernote.min.js", function () {
			$.getScript("/public/js/summernote/lang/summernote-zh-CN.min.js", function () {
				$("<link>").attr({ 
					rel: "stylesheet",
					type: "text/css",
					href: "/public/js/summernote/summernote.css"
				}).appendTo("head");
				$('.summernote-ueditor-loading').remove();
				$('.summernote_editor').each(function () {
					var editor_id   = $(this).attr('id');
					var placeholder = $(this).attr('placeholder');
					$('#' + editor_id).summernote({
						lang: 'zh-CN',
						placeholder: placeholder,
						height: 180,
						toolbar: [ ['common', ['style','bold','ol','link','picture','clear','fullscreen']] ],
						callbacks: {
							onChange:function (contents, $editable) {
								var code = $('#' + editor_id).summernote("code");
								$(this).val(code);
								// $('#' + editor_id).val(contents);
							},
							onImageUpload: function(files) {
								upload_editor_image(files[0], editor_id);
							},
							onPaste: function(ne) {
								// 清除HTML格式
								var bufferText = ((ne.originalEvent || ne).clipboardData || window.clipboardData).getData('Text/plain');  
	                            ne.preventDefault ? ne.preventDefault() : (ne.returnValue = false);  
	                            // Firefox fix  
	                            setTimeout(function () {  
	                                document.execCommand("insertText", false, bufferText);  
	                            }, 10);
							}
						}
					});
				});
			});
		});
	}
});





